class Order < ActiveRecord::Base
  belongs_to :user
  belongs_to :address
  belongs_to :logistic
  has_many   :line_items,:dependent=>:delete_all
  before_save :calculate_logistic_fee,:find_agent_by_code,:check_status
  attr_accessor :code
  #  has_and_belongs_to_many :products, :join_table =>:line_items

  ALIPAY = 1
  BANK = 2
  POST = 3


  PAYTYPE = [
    [ "支付宝",   ALIPAY ],
    [ "银行转账",   BANK ],
    [ "邮局汇款",   POST ]
  ]

  SHIPPING_TYPE = [
    [ "快递",   1 ],
    [ "邮政",   2 ],
    [ "自取",   3 ]
  ]

  STATUS = [

    [ "待付款", 1],
    [ "已付款待发货",2],
    [ "已发货",3],
    [ "已取消",4 ],
    [ "交易完成",5]

  ]

  def add_line_items_from_cart(cart)
    cart.items.each do |item|
      li = LineItem.from_cart_item(item)
      line_items << li
    end
  end

  def total_price
    line_items.inject(0) { |sum,item| sum+item.total_price } + self.logistics_fee
  end

  def discount_total_price
    self.total_product_price * self.discount + self.logistics_fee
  end

  def discount_product_price
    self.total_product_price * self.discount
  end

  def total_product_price
    line_items.inject(0) { |sum,item| sum+item.total_price }
  end

  def total_item
    line_items.inject(0) { |sum,item| sum+item.quantity }
  end

  def self.filter_order(status,start_date,end_date)
    self.find(:all,:conditions=>['status = ? and created_at between ? and ?',status,start_date,end_date])
  end

  def set_status_paid
    self.status = 2
  end

  def set_status_complate
    self.status = 5
  end

  def gc_product
    self.line_items.each do |li|
      li.product.update_quantity(li.quantity)
    end
  end

  def lock_product
    self.line_items.each do |li|
      li.product.update_quantity(-(li.quantity))
    end
  end


  private

 
  def find_agent_by_code
    return unless self.code
    user = User.find(:first,:conditions=>["code = ?",self.code])
    self.discount = user.discount if user
  end

  def count_agent_gain
    return unless self.agent_id
    user = User.find(agent_id)
    if user
      user.account += self.total_product_price * COMMISSION
      user.save
    end
  end

  def calculate_logistic_fee
    if self.logistic_id && self.address_id && self.total_item <= self.logistic.free_quantity
      logistic_fee = LogisticFee.find_by_province_id_and_logistic_id(self.address.province_id,self.logistic_id)
      self.logistics_fee = logistic_fee ? logistic_fee.fee : self.logistic.default_fee
    end
  end

  def check_status
    return if self.new_record?
    origin_order = Order.find(self.id)
    if  origin_order.status == self.status
      logger.error("origin_order.status =#{origin_order.status},self.status=#{self.status}")
      return
    end

    case self.status
    when 1
    when 2
      OrderMailer.deliver_confirm(self)
    when 3
      OrderMailer.deliver_sent(self)
    when 4
      gc_product
    when 5
      count_agent_gain
      OrderMailer.deliver_finish(self)
    end
  end
end
